<template>
  <div class="login-container">
    <!-- Logo 部分 -->
    <div class="logo-container">
      <van-image :src="logo" class="logo"></van-image>
    </div>

    <!-- 登录表单 -->
    <van-form @submit="onLogin">
      <van-cell-group inset>
        <van-field v-model="loginForm.username" name="username" placeholder="请输入用户名"
          :rules="[{ required: true, message: '请输入用户名' }]" />
        <van-field v-model="loginForm.password" type="password" name="password" placeholder="请输入密码" :rules="[
          { required: true, message: '请输入密码' },
          {
            pattern: /^[a-zA-Z0-9]{6,12}$/,
            message: '密码格式不正确'
          }
        ]" />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" :loading="loading" loading-text="登录中...">
          {{ loading ? '登录中...' : '登录' }}
        </van-button>
      </div>
    </van-form>

    <!-- 跳转到注册页面 -->
    <div class="register-link">
      <router-link to="/register">还没有账号？立即注册</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import logo from '../assets/logo.png'
import { showToast } from 'vant'
import request from '../utils/request'
import { useUserStore } from '../store/userStore'
import { loginApi } from '../api/user'
import router from '../router'

// 表单数据
const loginForm = ref({
  username: '',
  password: ''
})

// 加载状态
const loading = ref(false)

// 防抖定时器
let debounceTimer = null

const store = useUserStore()

// 登录提交
const onLogin = (values) => {
  // 如果正在加载中，阻止重复提交
  if (loading.value) {
    return
  }

  // 设置加载状态
  loading.value = true

  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }

  // 添加防抖延迟
  debounceTimer = setTimeout(() => {
    // 这里可以添加登录逻辑
    loginApi({
      "username": values.username,
      "password": values.password
    })
      .then((res) => {
        store.setUser(res.data)
        // 登录成功后的处理
        showToast('登录成功')

        // 可以在这里跳转到首页或其他页面
        router.push('/')
        console.log('用户信息' + JSON.stringify(store.user))
      })
      .catch((error) => {
        console.error(error)
        showToast('登录失败')
      })
      .finally(() => {
        // 重置加载状态
        loading.value = false
      })
  }, 300) // 300ms 防抖延迟
}
</script>

<style scoped>
.login-container {
  padding: 20px 0;
}

.logo-container {
  text-align: center;
  margin-bottom: 20px;
}

.logo {
  width: 100px;
  height: 100px;
  object-fit: contain;
}

.register-link {
  text-align: center;
  margin-top: 20px;
}

.register-link a {
  color: #1989fa;
  text-decoration: none;
}
</style>